#include <QGraphicsItem>

#include "UIWindow.h"
#include "UITouch.h"

class UITouchPrivate {
    public:
        QGraphicsItem *view;
        UIWindow *window;

        QPointF currentPos;
        QPointF startPos;
        quint16 tapCount;

        QDateTime timestamp;
        UITouchPhase phase;
        QTime time;
};

UITouch::UITouch (UIWindow *window, QGraphicsItem *view) 
    : d(new UITouchPrivate)
{
    d->view = view;
    d->tapCount = 0;
    d->window = window;
    d->phase = UITouchPhaseCancelled;
    d->timestamp = QDateTime::currentDateTime();
}

UITouch::~UITouch() {
    delete d;
}

void UITouch::start (const QPointF& pos) {
    if (!d->time.isNull()) {
        // Reset Tap Count if user is not Tapping
        if (d->time.elapsed() >= kUITouchMultiTapTime)
            d->tapCount = 0;
    }

    d->timestamp = QDateTime::currentDateTime();
    d->phase = UITouchPhaseBegan;
    d->startPos = pos;
    d->tapCount++;
    d->time.restart();
}

void UITouch::move (const QPointF& pos) {
    d->timestamp = QDateTime::currentDateTime();
    d->phase = UITouchPhaseMoved;
    d->currentPos = pos;
}

void UITouch::stop (void) {
    d->timestamp = QDateTime::currentDateTime();
    d->phase = UITouchPhaseEnded;
    d->time.restart();
}

quint16 UITouch::tapCount (void) const {
    return(d->tapCount);
}

qreal UITouch::startX (void) const {
    return(d->startPos.x());
}

qreal UITouch::startY (void) const {
    return(d->startPos.y());
}

QPointF UITouch::startPos (void) const {
    return(d->startPos);
}

qreal UITouch::currentX (void) const {
    return(d->currentPos.x());
}

qreal UITouch::currentY (void) const {
    return(d->currentPos.y());
}

QPointF UITouch::currentPos (void) const {
    return(d->currentPos);
}

qreal UITouch::deltaX (void) const {
    return(d->currentPos.x() - d->startPos.x());
}

qreal UITouch::deltaY (void) const {
    return(d->currentPos.y() - d->startPos.y());
}

qreal UITouch::absDeltaX (void) const {
    return(qAbs(d->currentPos.x() - d->startPos.x()));
}

qreal UITouch::absDeltaY (void) const {
    return(qAbs(d->currentPos.y() - d->startPos.y()));
}

UITouchPhase UITouch::phase (void) const {
    return(d->phase);
}

int UITouch::timeElapsed (void) const {
    return(d->time.elapsed());
}

QDateTime UITouch::timestamp (void) const {
    return(d->timestamp);
}

UIWindow *UITouch::window (void) const {
    return(d->window);
}

QGraphicsItem *UITouch::view (void) const {
    return(d->view);
}

